#include<iostream>
#include<string>
#include<unistd.h>
#include<pthread.h>

// 抢票逻辑，10000张票，5个线程抢
class Ticket{
public:
    Ticket():tickets(1000){
        pthread_mutex_init(&mtx, nullptr);
    }
    bool GetTicket(){
        bool ret = true;
        pthread_mutex_lock(&mtx);//加锁
        if(tickets > 0){
            usleep(1000);
            printf("我是[%ld]，我要抢的票是 %d\n", pthread_self(), tickets--);
            printf("");
        }
        else{
            printf("票已售完！\n");
            ret = false;
        }
        pthread_mutex_unlock(&mtx);//解锁
        return ret;
    }
    ~Ticket(){
        pthread_mutex_destroy(&mtx);
    }
private:
    int tickets;
    pthread_mutex_t mtx;
};

void* ThreadRun(void* args){

    Ticket* t = (Ticket*)args; 

    std::string tname = (char*)args;

    while(true){
        if(!t->GetTicket()){
            break;
        }
        else{
            continue;
        }
    }
}
int main(){
    Ticket* t = new Ticket();
    pthread_t tid[5];
    for(int i =0;i<5;i++){
        int* id = new int(i);
        pthread_create(tid + i, nullptr, ThreadRun, (void*)t);
    }
    for(int i =0; i< 5; i++){
        pthread_join(tid[i], nullptr);
    }
    return 0;
}
